import { validInt, validFloat, validateNull } from '@tapui/utils/validate'

// 是否是的正整数
export function checkPositiveInt(rule, value, callback) {
  if (!value) {
    callback()
    return true
  }
  value += ""
  if (!validInt(value)) {
    callback(new Error('请输入整数'))
  } else if (value.length >= 2 && (value.charAt(0) === "0")) {
    callback(new Error('请输入正确格式'))
  } else {
    callback()
  }
}

// 是否是的正数、保留四位小数
export function checkPositiveFloat(rule, value, callback) {
  if (!value) {
    callback()
    return true
  }
  let floatNum = parseInt(rule.floatNum)
  value += ""
  if (!validFloat(value)) {
    callback(new Error('请输入正数'))
  } else if (value.indexOf(".") !== -1 && value.split('.')[1].length > floatNum) {
    callback(new Error(`只保留${floatNum}位小数`))
  } else if (value.split('.')[0].length >= 2 && (value.split('.')[0].charAt(0) === "0")) {
    callback(new Error('请输入正确格式'))
  } else {
    callback()
  }
}

// ECP合同编号
export function checkECPCode(rule, value, callback) {
  if (!value) {
    callback()
    return true
  }
  value += ""
  let r = /^[A-Z]{2}\d{11}$/
  let regExpRes = value.match(r)
  if (!regExpRes) {
    callback(new Error('ECP合同编号13个字符，前2个字符是大写字母，后11个字符是数字'))
  } else {
    callback()
  }
}

// 采购订单编号编号
export function checkPurChaseCode(rule, value, callback) {
  if (!value) {
    callback()
    return true
  }
  value += ""
  let r = /^\d{10}$/
  let regExpRes = value.match(r)
  if (!regExpRes) {
    callback(new Error('采购订单编号10个字符，10个字符是数字'))
  } else {
    callback()
  }
}

// 客户采购订单编号编号
export function checkCustomerPurChaseCode(rule, value, callback) {
  if (!value) {
    callback()
    return true
  }
  value += ""
  let r = /^[A-Z]{2}\d{12}$/
  let regExpRes = value.match(r)
  if (!regExpRes) {
    callback(new Error('客户采购单编号14个字符，前2个字符大写字母，后12个字符是数字'))
  } else {
    callback()
  }
}

export function getStrByteLength(rule, value, callback, lengthLimit) {
  let str = value + ""
  let bytesCount = 0
  for (let i = 0, n = str.length; i < n; i++) {
    let c = str.charCodeAt(i)
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      bytesCount += 1
    } else {
      bytesCount += 2
    }
  }
  if (bytesCount > lengthLimit) {
    callback(new Error(`长度不能超过${lengthLimit}个字节`))
  } else {
    callback()
  }
}

export default {
  checkPositiveInt, checkPositiveFloat, checkECPCode, checkPurChaseCode, checkCustomerPurChaseCode, getStrByteLength
}
